package com.example.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.Lesson007Mapper;
import com.example.po.Lesson007PO;
import com.example.service.Lesson007Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/*
@description:
@ClassName Lesson007ServiceImpl
@author chen
@create 2025-06-24 18:18
@Version 1.0
*/
@Service
public class Lesson007ServiceImpl extends ServiceImpl<Lesson007Mapper, Lesson007PO> implements Lesson007Service
{
    @Resource
    private TransactionTemplate transactionTemplate;

    @Transactional
    @Override
    public void bigTransaction() throws InterruptedException
    {
        // 1、getData()方法模拟一个比较耗时的获取数据的操作，这个方法内部会休眠5秒
        String data = this.getData();
        // 2、将上面获取到的数据写入到db中
        Lesson007PO po = new Lesson007PO();
        po.setId(UUID.randomUUID().toString());
        po.setData(data);
        this.save(po);
    }


    public String getData() throws InterruptedException
    {
        //休眠5秒
        TimeUnit.SECONDS.sleep(5);
        return UUID.randomUUID().toString();
    }

    @Override
    public void smallTransaction() throws InterruptedException
    {
        // 1、调用getData()方法，讲获取的数据写到db中，假设 getData方法比较耗时，比如耗时 5秒
        String data = this.getData();

        // 2、将上面获取到的数据写入到db中
        Lesson007PO po = new Lesson007PO();
        po.setId(UUID.randomUUID().toString());
        po.setData(data);

        // this.transactionTemplate.executeWithoutResult可以传入一个Consumer，这个Consumer表述需要在事务中执行的业务操作
        this.transactionTemplate.executeWithoutResult(action -> this.save(po));
    }
}
